package naga.x.platform2.app;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import naga.x.platform2.app.model.Code;
import naga.x.platform2.app.model.GameServer;
import naga.x.platform2.app.support.CodeSupport;
import naga.x.platform2.app.support.GameServerSupport;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.PlatformUtils;
import naga.x.platform2.utils.StringUtils;

@Controller
public class CodeController {

	@Autowired
	private GameServerSupport gameServers;
	@Autowired
	private CodeSupport support;
	
	public static final Logger LOG = LoggerFactory.getLogger(CodeController.class);
	
	/**
	 * 领取礼包
	 */
	@RequestMapping(path = RequestPath.CODE_REQUEST, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object requestCode(String channel, Integer sid, Long pid, String code, String sign) {
		if (StringUtils.isEmpty(code)) {
			return PlatformUtils.newError(CodeSupport.CODE_BAD_REQUEST);
		}
		GameServer gs = gameServers.get(sid);
		if (gs == null) {
			return PlatformUtils.newError(CodeSupport.CODE_BAD_REQUEST);
		}
		if (pid == null) {
			return PlatformUtils.newError(CodeSupport.CODE_BAD_REQUEST);
		}
		Channel chnl = Channel.forCode(channel);
		Map<String, String> map = new TreeMap<>();
		map.put("channel", channel);
		map.put("sid", String.valueOf(sid));
		map.put("pid", String.valueOf(pid));
		map.put("code", code);
		String s = PlatformUtils.makeSign(gs, map);
		if (!s.equals(sign)) {
			return PlatformUtils.newError(CodeSupport.CODE_BAD_REQUEST);
		}
		try {
			Code c = support.receive(code, pid, chnl);
			Object res = PlatformUtils.newResponse("content", c.getContent());
			LOG.info("[CODE RECEIVED]ID[{}]CODE[{}]SERVER[{}]PLAYER[{}]CHANNEL[{}]", c.getId(), c.getCode(), sid, pid, channel);
			return res;
		} catch (AppException e) {
			return PlatformUtils.newError(e.getCode());
		}
	}
	
	
}
